package ch13.logevent;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

/**
 * Created by zc on 2016/6/2.
 */
public class LogEventBroadcaster {
    private final EventLoopGroup group;
    private final Bootstrap bootstrap;
    private final File file;

    public LogEventBroadcaster(InetSocketAddress address,
                               File file) {
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new LogEventEncoder(address));

        this.file = file;
    }

    public void run() throws InterruptedException, IOException {
        Channel channel = bootstrap.bind(0).syncUninterruptibly().channel();
        System.out.println("LogEventBroadcaster (" + file.getName() + ") running on port 9999.");
        long pointer = 0;

        while(true){
            long len = file.length();
            if(len < pointer) {
                pointer = len;
            } else if(len > pointer){
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                raf.seek(pointer);
                String line;
                while((line = raf.readLine())!=null){
                    System.out.println(line);
                    channel.writeAndFlush(new LogEvent(null,-1,
                            file.getAbsolutePath(), line));
                }
                pointer = raf.getFilePointer();
                raf.close();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex){
                Thread.interrupted();
                break;
            }
        }
    }

    public void stop(){
        group.shutdown();
    }

    public static void main(String[] args){
        LogEventBroadcaster broadcaster =
                new LogEventBroadcaster(new InetSocketAddress("255.255.255.255",9999),
                        new File("/temp/syslog"));
        try {
            broadcaster.run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            broadcaster.stop();
        }

    }
}
